package com.sangmo.fts;

import com.sangmo.boot.auth.core.AbstractAuthorizeService;
import com.sangmo.boot.auth.core.handlers.AuthorizeCodeHandler;
import com.sangmo.boot.auth.core.handlers.AuthorizeHandler;
import com.sangmo.boot.auth.core.handlers.impl.DefaultAuthorizeCodeHandler;
import com.sangmo.boot.auth.core.handlers.impl.DefaultAuthorizeHandler;
import com.sangmo.boot.framework.cache.meta.Cache;
import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.fts.config.AccessAspect;
import com.sangmo.fts.restructure.aspect.TrainingProcessAspect;
import com.sangmo.fts.user.service.AuthorizeUserService;
import com.sangmo.fts.user.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig {

    @Bean
    public Map authClientHandlers() {
        Map handlers = new HashMap();
        handlers.put("default", defaultAuthorizeHandler());
        return handlers;
    }

    @Bean
    public Map codeClientHandlers() {
        Map handlers = new HashMap();
        handlers.put("default", defaultAuthorizeCodeHandler());
        return handlers;
    }

    @Bean
    public AuthorizeHandler defaultAuthorizeHandler() {
        return new DefaultAuthorizeHandler();
    }

    @Bean
    public AuthorizeCodeHandler defaultAuthorizeCodeHandler() {
        return new DefaultAuthorizeCodeHandler();
    }

    @Bean
    public AuthorizeUserService authorizeUserService() {
        return new AuthorizeUserService();
    }

    @Bean
    public AbstractAuthorizeService abstractAuthorizeService(AuthorizeUserService authorizeUserService) {
        return new AbstractAuthorizeService<User>() {

            @Override
            @Cache(value = 60 * 5, parametrizedClass = UserSession.Authorize.class, parameterClass = {User.class})
            public UserSession.Authorize<User> findAuthorize(String identity, String token) {
                return authorizeUserService.findAuthorize(identity, token);
            }

            @Override
            public User doAuthentication(String identity, String password) {
//                return authorizeUserService.doAuthentication(identity, password);
                return authorizeUserService.doExternalAuthentication(identity, password);
            }

            @Override
            public User createIfNotExists(String identity) {
                return authorizeUserService.createIfNotExists(identity);
            }
        };
    }

    @Bean
    public AccessAspect accessAspect() {
        return new AccessAspect();
    }

    @Bean
    public TrainingProcessAspect trainingProcessAspect() {
        return new TrainingProcessAspect();
    }
}
